package utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by lub_lenovo on 2017/8/8.
 */
public class FileUploadUtils {
    public static String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //文件上传的upload文件夹的绝对路径
        String path = request.getSession().getServletContext().getRealPath("upload");
        //文件夹下面添加二级目录，按照日期添加
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        String date=format1.format(new Date());//2017-08-08
        //设置路径为 upload+date，如：/upload/2017-08-08/
        path+="/"+date;
//        文件原始名称
        String fileName = file.getOriginalFilename();
//        文件名的后缀
        String ext=fileName.substring(fileName.lastIndexOf('.'));
//        新文件名称
//        fileName=String.valueOf(System.currentTimeMillis())+ext;
        fileName= IDUtils.genImageName()+ext;

        File dir = new File(path,fileName);

        if(!dir.exists()){
            dir.mkdirs();
        }

        //MultipartFile自带的解析方法
        file.transferTo(dir);
        return request.getContextPath()+"/upload/"+date+"/"+fileName;
    }

    public static String upload_qn(String filePath){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "U888E2m2dmlI74HKZozW5NxXlptWi34hiiXWlCUA";
        String secretKey = "pi2OlN8DtOGGDbX_87INqgo9thtIgDxGObhaR5rj";
        String bucket = "jztj";
        String tempDomain="http://otzzy67z1.bkt.clouddn.com/";
        //如果是Windows情况下，格式是 D:\\qiniu\\test.png
        //String localFilePath = "D:\\1.jpg";
        String localFilePath = filePath;
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            //putRet就是上传到七牛云后的图片名称。前面拼接上自己空间的临时域名就可以访问到图片了
            return tempDomain+putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return "";
    }

    public static String upload_qn_stream(MultipartFile file){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
        String accessKey = "U888E2m2dmlI74HKZozW5NxXlptWi34hiiXWlCUA";
        String secretKey = "pi2OlN8DtOGGDbX_87INqgo9thtIgDxGObhaR5rj";
        String bucket = "jztj";
        String tempDomain="http://otzzy67z1.bkt.clouddn.com/";

//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        try {
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return tempDomain+putRet.hash;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
